package aes.general;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

/**
 * The Class TeacherControl. This calss will process everything the teacher does.
 * This class is responsible of the functionality of the things.
 * Uses the MVC model. 
 */
public class TeacherControl {

	
	/**
	 * The temp.
	 */
	private static ArrayList<String> temp = new ArrayList<String>();
	
	/**
	 * The curses.
	 */
	private static ArrayList<String> curses = new ArrayList<String>();
	
	/**
	 * The crsname.
	 */
	private static ArrayList<String> crsname = new ArrayList<String>();
	
	/**
	 * The curse id.
	 */
	private static ArrayList<String> curseID = new ArrayList<String>();
	
	/**
	 * The Qid.
	 */
	private static ArrayList<String> Qid = new ArrayList<String>();
	
	/**
	 * The Active exams.
	 */
	private static ArrayList<String> NonActiveExams = new ArrayList<String>();
	
	/**
	 * The Stat exam.
	 */
	private static ArrayList<String> StatExam = null;
	
	/**
	 * The Statistics.
	 */
	private static ArrayList<String> Statistics =null;
	
	private static ArrayList<String> Examinfo =null;
	/**
	 * The Running exams.
	 */
	private static ArrayList<String> RunningExams = new ArrayList<String>();
	
	/**
	 * The nonapp exams.
	 */
	private static ArrayList<String> nonappExams = null;
	
	/**
	 * The Info.
	 */
	private static ArrayList<Integer> grades = null;
	
	
	private static Vector<Vector<String>> Info = null;

	
	/**
	 * The Question.
	 */
	private static String Question;
	
	/**
	 * The Description.
	 */
	private static String Description;
	
	/**
	 * The Ans1.
	 */
	private static String Ans1;
	
	/**
	 * The Ans2.
	 */
	private static String Ans2;
	
	/**
	 * The Ans3.
	 */
	private static String Ans3;
	
	/**
	 * The Ans4.
	 */
	private static String Ans4;
	
	/**
	 * The check.
	 */
	private static boolean check;
	
	/**
	 * The check1.
	 */
	private static boolean check1 = false;

    /**
	 * Called from TeacherExamPanel class. 
	 * Gets the courses method is retrieving the name of the courses 
	 * and the course ID for when the teacher is composing exam. 
	 * The teacher will then choose the correct course the exam belongs to. 
	 * 
	 * @param courses
	 *            the courses
	 * @return the courses
	 */
    public static void getCourses(ArrayList<String> courses) {

        try {
                GuiControlBeta.getClient().openConnection();
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }

        Msg request = new Msg(courses, "401");
        GuiControlBeta.getClient().handleMessageFromClientUI(request);
}

    /**
     * This method is setting the course ID and course name after querying
     * it from the Data Base
     *
     * @param msg the msg
     */
    @SuppressWarnings("unchecked")
    public static void RecieveCourses(Object msg) {
            crsname.clear();
            curseID.clear();
            temp = (ArrayList<String>) ((Msg) msg).getMsg();

            for (int i = 0; i < temp.size()-1; i++) {
                    curseID.add(temp.get(i));
                    crsname.add(temp.get(++i));
            }
    }
	
	/**
	 * Returning The course ID and course name that was set in the method above.
	 * 
	 * @return the curses
	 */
	public static ArrayList<String> getCurses() {
		return curses;
	}
	
	 /**
	 * Called from TeacherExamPanel class. 
	 * Gets the questions related to the subject chosen by the teacher
	 * when composing exam, so the teacher will be able to choose 
	 * which questions he/she wants to add to the exam.
	 * 
	 * @param req
	 *            the Subject id 
	 * @return the questions
	 */
 	public static void getQuestion(String req) {

	     try {
	             GuiControlBeta.getClient().openConnection();
	     } catch (IOException e) {
	             // TODO Auto-generated catch block
	             e.printStackTrace();
	     }               
	     Msg request = new Msg(req, "402");
	     GuiControlBeta.getClient().handleMessageFromClientUI(request);
	 }
	 
	/**
	 * Setting the parameters for each question
	 * that returned from the querying of the data base.
	 * Recieves questions, description and the possible answers.
	 * 
	 * @param msg
	 *            the questions and related
	 */
	@SuppressWarnings("unchecked")
	public static void RecieveQuestions(Object msg) {
		temp = (ArrayList<String>) ((Msg) msg).getMsg();
		for (int i = 0; i < temp.size(); i++){
			Question = temp.get(i);
			Description = temp.get(++i);
			Ans1 = temp.get(++i);
			Ans2 = temp.get(++i);
			Ans3 = temp.get(++i);
			Ans4 = temp.get(++i);
		}
	}

	/**
	 * Gets the question.
	 * 
	 * @return the question
	 */
	public static String getQuestion() {
		return Question;
	}

	/**
	 * Gets the description.
	 * 
	 * @return the description
	 */
	public static String getDescription() {
		return Description;
	}

	/**
	 * Gets the ans1.
	 * 
	 * @return the ans1
	 */
	public static String getAns1() {
		return Ans1;
	}

	/**
	 * Gets the ans2.
	 * 
	 * @return the ans2
	 */
	public static String getAns2() {
		return Ans2;
	}

	/**
	 * Gets the ans3.
	 * 
	 * @return the ans3
	 */
	public static String getAns3() {
		return Ans3;
	}

	/**
	 * Gets the ans4.
	 * 
	 * @return the ans4
	 */
	public static String getAns4() {
		return Ans4;
	}

	/**
	 * Called from TeacherExamPanel class. 
	 * Inserting the exam to the data base after the teacher has created it. 
	 * 
	 * @param exam
	 *            the exam
	 */
	public static void AddExam(Exam exam) {
	
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		Msg request = new Msg(exam, "403");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

	/**
	 * A return msg from the insertion of the above method.
	 * If exam with the same ID that the teacher chose exists
	 * then it sets the param 'check' to false, otherwise
	 * the exam has been saved and stored to data base successfully.
	 * 
	 * @param msg
	 *            the msg
	 */
	public static void ExamIdError(Object msg) {
		if(((Msg)msg).getMsg().equals("error"))
			check = false;
		else check = true;
	}
	
	public static boolean isCheck() {
		return check;
	}

	public static void setCheck(boolean check) {
		TeacherControl.check = check;
	}

	/**
	 * Returning the insertion query answer.
	 * 
	 * @return true, if exam successful stored to data base
	 */
	public static boolean ExamIdError(){
		return check;
	}

	/**
	 * Called from TeacherActivationPanel class.
	 * Request for non active exams for the teacher to choose from them
	 * and set them an activation code.
	 * 
	 * @param active
	 *            the active
	 */
	public static void RequestActiveExams(ArrayList<String> active) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(active, "404");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

	/**
	 * Receives the non active exams that were querying 
	 * in the method above.
	 * 
	 * @param msg
	 *            the msg
	 */
	@SuppressWarnings("unchecked")
	public static void SetActExam(Object msg) {
		NonActiveExams = (ArrayList<String>) ((Msg)msg).getMsg();
	}
	
	/**
	 * Gets the non active exams.
	 * 
	 * @return the active exams
	 */
	public static ArrayList<String> getActiveExams() {
		return NonActiveExams;
		
	}
	
	/**
	 * A return msg from the insertion of an activation
	 * code. If the activation code is already exists in one of the
	 * exams, so then the parameter 'check1' is set to false, 
	 * otherwise its set to true.
	 * 
	 * @param msg
	 *            the msg
	 */
	public static void ActivationAnswer(Object msg){
		if(((Msg)msg).getMsg().equals("error"))
			check1 = false;
		else check1 = true;
	}
	
	/**
	 * Activation answer. If the activation code is unique
	 * so the param is true and the activation code can be 
	 * assign to the exam.
	 * 
	 * @return true, if successful
	 */
	public static boolean ActivationAnswer(){
		return check1;
	}

	/**
	 * Called from TeacherActivationPanel class.
	 * When the teacher is assigning an activation code
	 * this method is querying the data base for if the 
	 * same activation code already exist and if not assigning the activation 
	 * code that was given by the teacher.
	 * 
	 * @param examToActive
	 *            the exam to active
	 */
	public static void SetActivationCode(ArrayList<String> examToActive) {
		check1 = false;
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(examToActive, "405");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

	/**
	 * Called from TeacherStatPanel class.
	 * Request exam id's so the teacher
	 * can chose the exam she/he wants to see statistical 
	 * information about.
	 * 
	 * @param finishedExams
	 *            the finished exams
	 */
	public static void RequestStatExams(String Tid) {
			try {
				GuiControlBeta.getClient().openConnection();
			} catch (IOException e) {
				System.out.println("406 Can't Open Connection");
					e.printStackTrace();
			}
			String qery = new String("Select distinct E.ExamId from exam E,finishedexam Fe where E.ExamId = Fe.ExamId and E.TID = "+ Tid);
			Msg request = new Msg(qery,"406");
			GuiControlBeta.getClient().handleMessageFromClientUI(request);
		}


	/**
	 * Sets the exam id's that were recieved from the data base 
	 * after the call of the method above.
	 * 
	 * @param msg
	 *            the msg
	 */
	
	
	public static void SetStatExamInfo(Object msg) {
			SetStatExam((ArrayList<String>) ((Msg)msg).getMsg());	
	}
	
	public static void SetStatExam(ArrayList<String> examinfo) {
		StatExam = 	examinfo;
}
	
	/**
	 * Gets the exam id's.
	 * 
	 * @return the exam id's
	 */
	public static ArrayList<String> getStatExam() {
		return StatExam;
	}





	/**
	 * Called from TeacherRequestExamPanel class.
	 * Request active exams that the teacher can extend time to.
	 * 
	 * @param active
	 *            the active
	 */
	public static void RequestExams(ArrayList<String> active) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(active, "408");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);	
	}

	/**
	 * Sets the activated exams after queryiny the data base follow the call
	 * of the method above.
	 * 
	 * @param msg
	 *            the msg
	 */
	@SuppressWarnings("unchecked")
	public static void SetActivatedExams(Object msg) {
		RunningExams = (ArrayList<String>) ((Msg)msg).getMsg();	 
	}
	
	/**
	 * Gets the running exams.
	 * 
	 * @return the running exams
	 */
	public static ArrayList<String> getRunningExams() {
		return RunningExams;
	}

	/**
	 * Called from TeacherRequestExamPanel class.
	 * Sets the request and the time desired to extend.
	 * 
	 * @param extendExam
	 *            the new request
	 */
	public static void setRequest(ArrayList<String> extendExam) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(extendExam, "409");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);	
	}


	/**
	 * 
	 * Sets the not approved exams after querying the data base for it
	 * follow the call of the method GetNonApprovedExams down below.
	 * 
	 * @param msg
	 *            the msg
	 */
	@SuppressWarnings("unchecked")
	public static void SetNotApprovedExams(Object msg) {
		SetnonAppdExams((ArrayList<String>) ((Msg)msg).getMsg());	
	}
	
	/**
	 * Called from TeacherApproveGradePanel class.
	 * Gets the non approved exams for the teacher so she/he can
	 * approve the grades of the students.
	 * 
	 * @return the not approved exams exams
	 */
	public static ArrayList<String> getNonappdExams() {
		return nonappExams;
	}
	
	/**
	 * Set non approved exams.
	 * 
	 * @param nonpexam
	 *            the not approved exams
	 */
	public static void SetnonAppdExams(ArrayList<String> nonpexam) {
		nonappExams = nonpexam;	
	}
	
	/**
	 * Called from TeacherFrame class.
	 * Gets the non approved exams of that teacher who requested
	 * for him/her to approve the grades.
	 * 
	 * @param TeacherId
	 *            the teacher id
	 */
	public static void GetNonApprovedExams(String TeacherId) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(TeacherId, "410");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

	/**
	 * Called from TeacherApproveGradePanel class. 
	 * Gets the not approved exam's info.
	 * 
	 * @param selectedItem
	 *            the selected exam
	 * @return the not approved exam's info
	 */
	public static void getNotapproveInfo(Object selectedItem) {
		try {
			GuiControlBeta.getClient().openConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}				
		Msg request = new Msg(selectedItem, "411");
		GuiControlBeta.getClient().handleMessageFromClientUI(request);
	}

   /**
	 * Called from TeacherStatPanel class.
	 * Gets the approved exam information fot the teacher to see
	 * the statistics.
	 * 
	 * @param ExamId
	 *            the exam id
	 */
   public static void GetApprovedInfo(String ExamId) {
       try {
               GuiControlBeta.getClient().openConnection();
       } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
       }                              
       Msg request = new Msg(ExamId, "411");
       GuiControlBeta.getClient().handleMessageFromClientUI(request);
   }
    
	
   /**
	 * Sets the approved info.
	 * 
	 * @param msg
	 *            the msg
	 */
   @SuppressWarnings("unchecked")
   public static void SetNotApprovedinfo(Object msg) {
           Setinfo((Vector<Vector<String>>) ((Msg)msg).getMsg());
   }

   /**
	 * Gets the info.
	 * 
	 * @return the info
	 */
   public static Vector<Vector<String>> getInfo() {
           return Info;
   }
   
   /**
	 * Set info.
	 * 
	 * @param inmsg
	 *            the inmsg
	 */
   public static void Setinfo(Vector<Vector<String>> inmsg) {
       Info = inmsg;
   }
   
   /**
	 * Called from TeacherChangeGradePanel class 
	 * The teacher changes the grade manually.
	 * Sending new grade to qeury the data base..
	 * 
	 * @param approved
	 *            the approved
	 */
   public static void InsertNewGrade(ArrayList<String> approved) {
	   try {
             GuiControlBeta.getClient().openConnection();
     } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
     }                              
     Msg request = new Msg(approved, "412");
     GuiControlBeta.getClient().handleMessageFromClientUI(request);
     }
     
   /**
    * Called from TeacherExamPanel class.
    * Gets the question id's.
    *
    * @param courses the coureses id's
    */
   public static void getQid(ArrayList<String> courses) {
     try {
             GuiControlBeta.getClient().openConnection();
     } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
     }     
     
     Msg request = new Msg(courses, "413");
     GuiControlBeta.getClient().handleMessageFromClientUI(request);   
     }
	 
	 /**
	 * Getting the course id after querying the data base follow
	 * the call of the above method
	 * 
	 * @return the course id
	 */
 	public static ArrayList<String> getCurseId() {
         return curseID;
	 }

	 /**
	 * Gets the course name.
	 * 
	 * @return the course name
	 */
 	public static ArrayList<String> getCourseName() {
	         return crsname;
	 }
	 
     /**
		 * Setting the question id after querying the data base follow
		 * the call of the above method
		 * Sets the question id.
		 * 
		 * @param msg
		 *            the msg
		 */
     @SuppressWarnings("unchecked")
     public static void SetQId(Object msg) {
             Qid = (ArrayList<String>) ((Msg) msg).getMsg();       
     }
    
     /**
		 * Gets the question ID.
		 * 
		 * @return the question ID
		 */
     public static ArrayList<String> getQid() {
             return Qid;
     }

	/**
	 * Call from TeacherApproveGradePanel class.
	 * The teacher has approved the exam and now it 
	 * inserted to the data base as approved exam.
	 * 
	 * @param infotoapprove
	 *            the exam info to approve
	 */
	public static void InserApprove(ArrayList<String> infotoapprove) {
		 try {
             GuiControlBeta.getClient().openConnection();
     } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
     }                              
     Msg request = new Msg(infotoapprove, "414");
     GuiControlBeta.getClient().handleMessageFromClientUI(request);
	 }

	/**
	 * Called from TeacherLockExamPanel class.
	 * Teacher is locking the specified exam.
	 * 
	 * @param examToLock
	 *            the exam id to lock
	 */
	public static void LockExam(String examToLock) {
		 try {
            GuiControlBeta.getClient().openConnection();
    } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }                              
    Msg request = new Msg(examToLock, "416");
    GuiControlBeta.getClient().handleMessageFromClientUI(request);	
	}

	/**
	 * Called from TeacherChangeGradePanel class.
	 * After teacher changes grade, need to sets the new grade.
	 * 
	 * @param gradeinfo
	 *            the grade info
	 */
	public static void SetNewGrade(ArrayList<String> gradeinfo) {
		 try {
	            GuiControlBeta.getClient().openConnection();
	    } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	    }                              
	    Msg request = new Msg(gradeinfo, "415");
	    GuiControlBeta.getClient().handleMessageFromClientUI(request);
		
	}

	/**
	 * Called from TeacherApproveGradePanel class.
	 * Request grades from the data base for the teacher to see for approvement.
	 * 
	 * @param string
	 *            the grades
	 */
	public static void RequestGrades(String string) {
				 try {
		             GuiControlBeta.getClient().openConnection();
		     } catch (IOException e) {
		             // TODO Auto-generated catch block
		             e.printStackTrace();
		     }     
		     Msg request = new Msg(string, "417");
		     GuiControlBeta.getClient().handleMessageFromClientUI(request);	
	}
	
	
	public static void setingsGradesStats(Object msg) {
		setGrades((ArrayList<Integer>) ((Msg) msg).getMsg());
		
	}


	public static ArrayList<Integer> getGrades() {
		return grades;
	}


	public static void setGrades(ArrayList<Integer> grades1) {
		grades = grades1;
	}
	
	
	public static ArrayList<Double> CulcStudentStats(ArrayList<Integer> grades) {
		
		int numofgrades = grades.size();
		ArrayList<Double> stats = new ArrayList<Double>();
		double avg;
		double median;
		int sum=0;
		for(Integer temp:grades){
			sum+=temp;
		}
	    
	    avg = sum/numofgrades;
	    
	    Collections.sort(grades);
	    if (grades.size() % 2 == 1){
		median = grades.get((grades.size()+1)/2-1);
		}
		else
		 {
			double lower = grades.get(grades.size()/2-1);
			double upper = grades.get(grades.size()/2);
			median= (lower + upper) / 2.0;	
		 }
	    stats.add(avg);
	    stats.add(median);
	    stats.add((double)numofgrades);
	    return stats;		
		
	}

	public static int[] getDistribution(ArrayList<Integer> grades)
	{
		int[] dis = new int[10];
		for(int i=0;i<grades.size();i++)
		{
			if(grades.get(i)!=100)
			dis[(grades.get(i)/10)]++;
			else
				dis[9]++;
		}
		return dis;
		
	}

	public static void getExamInfo(String Examid) {
		 try {
             GuiControlBeta.getClient().openConnection();
     } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
     }     
     Msg request = new Msg(Examid, "418");
     GuiControlBeta.getClient().handleMessageFromClientUI(request);	
		
	}

	public static void setExamInfoteacher(Object msg) {
		setExaminfo((ArrayList<String>) ((Msg) msg).getMsg());
		
	}

	public static ArrayList<String> getExaminfo() {
		return Examinfo;
	}

	public static void setExaminfo(ArrayList<String> examinfo1) {
		Examinfo = examinfo1;
	}

	
}
